// 缓存管理器实现
// @/utils/http/CacheManager.ts

import type { CacheItem } from '@/types/http'

export class CacheManager {
  private cache: Map<string, CacheItem>
  private timers: Map<string, number>
  private maxSize: number
  private defaultTTL: number

  constructor(options: {
    maxSize?: number
    defaultTTL?: number
  } = {}) {
    this.cache = new Map()
    this.timers = new Map()
    this.maxSize = options.maxSize || 100
    this.defaultTTL = options.defaultTTL || 5 * 60 * 1000 // 默认5分钟
  }

  // 获取缓存
  get<T = any>(key: string): T | null {
    const item = this.cache.get(key)
    
    if (!item) {
      return null
    }

    // 检查是否过期
    if (Date.now() > item.expireTime) {
      this.delete(key)
      return null
    }

    return item.data as T
  }

  // 设置缓存
  set<T = any>(key: string, data: T, ttl?: number): void {
    // 检查缓存大小
    if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
      // 删除最早的缓存项
      const firstKey = this.cache.keys().next().value
      if (firstKey) {
        this.delete(firstKey)
      }
    }

    const expireTime = Date.now() + (ttl || this.defaultTTL)
    
    // 清除旧的定时器
    this.clearTimer(key)
    
    // 设置新缓存
    this.cache.set(key, {
      data,
      timestamp: Date.now(),
      expireTime
    })

    // 设置自动清理定时器
    const timer = setTimeout(() => {
      this.delete(key)
    }, ttl || this.defaultTTL) as unknown as number

    this.timers.set(key, timer)
  }

  // 删除缓存
  delete(key: string): boolean {
    this.clearTimer(key)
    return this.cache.delete(key)
  }

  // 检查缓存是否存在
  has(key: string): boolean {
    const item = this.cache.get(key)
    if (!item) {
      return false
    }

    // 检查是否过期
    if (Date.now() > item.expireTime) {
      this.delete(key)
      return false
    }

    return true
  }

  // 清除所有缓存
  clear(): void {
    // 清除所有定时器
    this.timers.forEach((timer) => {
      clearTimeout(timer)
    })
    this.timers.clear()
    this.cache.clear()
  }

  // 获取缓存大小
  get size(): number {
    return this.cache.size
  }

  // 清理过期缓存
  prune(): void {
    const now = Date.now()
    const keysToDelete: string[] = []

    this.cache.forEach((item, key) => {
      if (now > item.expireTime) {
        keysToDelete.push(key)
      }
    })

    keysToDelete.forEach(key => this.delete(key))
  }

  // 获取所有缓存键
  keys(): string[] {
    return Array.from(this.cache.keys())
  }

  // 获取缓存统计信息
  getStats(): {
    size: number
    maxSize: number
    keys: string[]
    memoryUsage: number
  } {
    let memoryUsage = 0
    
    this.cache.forEach((item) => {
      try {
        memoryUsage += JSON.stringify(item).length * 2 // 粗略估计，UTF-16编码
      } catch {
        // 忽略无法序列化的对象
      }
    })

    return {
      size: this.cache.size,
      maxSize: this.maxSize,
      keys: this.keys(),
      memoryUsage
    }
  }

  // 清除定时器
  private clearTimer(key: string): void {
    const timer = this.timers.get(key)
    if (timer) {
      clearTimeout(timer)
      this.timers.delete(key)
    }
  }

  // 批量设置缓存
  setMany(items: Array<{ key: string; data: any; ttl?: number }>): void {
    items.forEach(({ key, data, ttl }) => {
      this.set(key, data, ttl)
    })
  }

  // 批量获取缓存
  getMany<T = any>(keys: string[]): Record<string, T | null> {
    const result: Record<string, T | null> = {}
    
    keys.forEach(key => {
      result[key] = this.get<T>(key)
    })

    return result
  }

  // 更新缓存过期时间
  touch(key: string, ttl?: number): boolean {
    const item = this.cache.get(key)
    
    if (!item) {
      return false
    }

    // 更新过期时间
    item.expireTime = Date.now() + (ttl || this.defaultTTL)
    
    // 重置定时器
    this.clearTimer(key)
    const timer = setTimeout(() => {
      this.delete(key)
    }, ttl || this.defaultTTL) as unknown as number
    
    this.timers.set(key, timer)
    
    return true
  }
} 